// 负责用户部分数据操作
// 导入操作数据库的配置
const db = require('../config/db');
const aes = require('../common/aes');
const Jwt = require('../common/jwt');
// 步骤：1.0 生成token  2. 校验token    token: 用户的临时身份（设置登录时效）

// 测试以下
// console.log('测试：',aes.aesDecrypt('1111','$2a$10$70FdA4ZbBTwei'));
// 导出当前数据模型
module.exports = {
    // 1. 注册
    register(admin_id, admin_acc, admin_pwd, admin_nick_name, admin_create_time) {
        // 检查代码有没有执行到此处
        return new Promise((resolve, reject) => {
            // 对密码加密
            let pwd = aes.aesEncrypt(admin_pwd);//加密
            // let pwd = admin_pwd
            // 判断账号是否存在
            db.query(`select admin_id from c_admin where admin_acc='${admin_acc}'`)
                .then(
                    rows => {
                        // rows 是个数组
                        // console.log('1.0',rows);// []
                        // 判断账号是否已经注册
                        if (rows.length == 0) {
                            // 表示没有注册 , 添加数据
                            db.query(`insert into c_admin(admin_id,admin_acc,admin_pwd,admin_nick_name,admin_create_time) values('${admin_id}','${admin_acc}','${pwd}','${admin_nick_name}','${admin_create_time}')`)
                                .then(
                                    result => {
                                        resolve({
                                            code: 200,
                                            msg: '注册管理员账号成功。',
                                            admin_nick_name
                                        })
                                    }
                                )
                                .catch(
                                    error => {
                                        reject({ code: 500, msg: '注册账号失败。', error })
                                    }
                                )
                        }
                        else {
                            // 表示已经注册
                            resolve({
                                code: 201,
                                msg: '该账号已经存在。请登录即可'
                            })
                        }
                    }
                )
                .catch(
                    err => {
                        reject({ code: 500, msg: '注册时查询账号失败。', err })
                    }
                )
        })
    },

    // 2. 登录
    login(admin_acc, admin_pwd) {
        return new Promise((resolve, reject) => {
            db.query(`select admin_acc,admin_pwd, admin_nick_name,admin_create_time, admin_id from c_admin where admin_acc = '${admin_acc}'`)
                .then(
                    rows => {
                        // console.log('1.0',rows);
                        // console.log(rows[0]);
                        // console.log(admin_pwd, rows[0].admin_pwd)
                        // rows[用户信息]
                        console.log('状态:', aes.aesDecrypt(admin_pwd, rows[0].admin_pwd));

                        // if(admin_pwd === rows[0].admin_pwd){
                        if (aes.aesDecrypt(admin_pwd, rows[0].admin_pwd)) {// 解密
                            // 生成token
                            let jwt = new Jwt(rows[0].admin_id, 120);
                            let token = jwt.getToken();
                            // 等于true表示登录成功
                            resolve({
                                code: 200,
                                msg: '登录管理员账号成功。',
                                token,
                                nick_name: rows[0].admin_nick_name
                            })
                        }
                        else {
                            // 否则 登录失败
                            resolve({
                                code: -1,
                                msg: '用户登录失败。'
                            })
                        }
                    }
                )
                .catch(
                    error => {
                        reject({ code: 500, msg: '查询用户失败。', error })
                    }
                )
        })
    },

    // 3. 注销(删除账号)
    remove(admin_id) {
        return new Promise((resolve, reject) => {
            db.query(`select admin_acc from c_admin where admin_id = '${admin_id}'`)
                .then(
                    rows => {
                        if (rows.length == 1) {
                            // 有 再删除
                            db.query(`delete from c_admin where admin_id = '${admin_id}'`)
                                .then(
                                    content => {
                                        resolve({
                                            code: 200,
                                            msg: '删除账号成功。',
                                            content
                                        })
                                    }
                                )
                                .catch(
                                    err => {
                                        reject({
                                            code: -1,
                                            msg: '删除账号失败。',
                                            err
                                        })
                                    }
                                )
                        }
                        else {
                            // 无 不用删除
                            resolve({
                                code: 404,
                                msg: '该账号不存在。'
                            })
                        }
                    }
                )
                .catch(
                    error => {
                        reject({
                            code: 500,
                            msg: '查询用户失败。',
                            error
                        })
                    }
                )
        })
    },

    // 4. 获取用户头像
    getPicUrl(admin_id) {
        return new Promise((resolve, reject) => {
            // 执行sql语句
            db.query(`select admin_picUrl from c_admin where admin_id = '${admin_id}'`)
                .then(
                    rows => {
                        let admin_url = rows[0].admin_picUrl;
                        // 执行符合条件的回调
                        resolve({
                            code: 200,
                            msg: '获取用户头像成功。',
                            admin_url
                        })
                    }
                )
                .catch(
                    err => {
                        reject({
                            code: -1,
                            msg: '获取用户头像失败。'
                        })
                    }
                )

        })
    },


    // 5. 设置用户头像
    setPicUrl(admin_id, admin_picUrl) {
        return new Promise((resolve, reject) => {
            // 修改用户头像
            let sql = `update c_admin set admin_picUrl= '${admin_picUrl}' where  admin_id= '${admin_id}'`;
            db.query(sql)
                .then(
                    content => {
                        resolve({
                            code: 200,
                            msg: '更新用户头像成功。',
                            content
                        })
                    }
                )
                .catch(
                    err => {
                        reject({
                            code: -1,
                            msg: '更新用户头像失败',
                            err
                        })
                    }
                )
        })
    },

    // 6. 找回密码
    findPwd(admin_acc, new_admin_pwd) {
        return new Promise((resolve, reject) => {
            let sql = `select admin_acc from c_admin where admin_acc = '${admin_acc}'`;
            db.query(sql)
                .then(
                    rows => {
                        if (rows.length == 1) {
                            //  重新设置密码
                            db.query(`update c_admin set admin_pwd= '${new_admin_pwd}' where  admin_acc= '${admin_acc}'`)
                                .then(
                                    content => {
                                        resolve({
                                            code: 200,
                                            msg: '重置密码成功。'
                                        })
                                    }
                                )
                                .catch(error => {
                                    reject({
                                        code: -1,
                                        msg: '重置密码失败。',
                                        error
                                    })
                                })
                        }
                        else {
                            resolve({
                                code: 404,
                                msg: '该账号不存在。'
                            })
                        }
                    }
                )
                .catch(
                    err => {
                        reject({
                            code: -1,
                            msg: '找回密码时，查询用户失败。',
                            err
                        })
                    }
                )
        })
    },

    // 7. 用户列表
    userList(page = 1, pageSize = 5) {
        let page_num = ((parseInt(page) - 1) * parseInt(pageSize))
        let page_size = (parseInt(pageSize))
        // 获取用户列表（部分）
        let sql = `select   id,
                            user_id,
                            user_acc,
                            user_pwd,
                            user_nick_name,
                            user_create_time,
                            user_picUrl,
                            user_age,
                            user_sex,
                            user_address from c_user limit ${page_num} , ${page_size}`
        return new Promise((resolve, reject) => {
            // 统计用户的数量
            db.query(`select count(*) as total from c_user`)
                .then(
                    (data) => {
                        return data[0] && data[0].total;
                    }
                )
                .then(
                    (total) => {
                        db.query(sql)
                            .then(
                                rows => {
                                    resolve({
                                        code: 200,
                                        msg: '获取用户列表成功。',
                                        result: [...rows],
                                        total
                                    })
                                },
                                err => {
                                    reject({
                                        code: -1,
                                        msg: '获取列表失败。',
                                        err
                                    })
                                }
                            )
                            .catch(
                                error => {
                                    reject({
                                        code: -1,
                                        msg: '获取列表失败。',
                                        err
                                    })
                                }
                            )
                    }
                )
        })
    },

    // 8. 删除用户
    deleteUser(user_id) {
        return new Promise((resolve, reject) => {
            db.query(`select user_id from c_user where user_id = '${user_id}'`)
                .then(
                    rows => {
                        if (rows.length == 1) {
                            // 存在
                            let sql = `delete from c_user where user_id = '${user_id}'`
                            db.query(sql)
                                .then(
                                    () => {
                                        resolve({
                                            code: 200,
                                            msg: '管理员删除用户成功。'
                                        })
                                    },
                                    err => {
                                        reject({
                                            code: -1,
                                            msg: '删除用户失败。',
                                            err
                                        })
                                    }
                                )
                        }
                        else {
                            resolve({
                                code: 404,
                                msg: '不存在该用户'
                            })
                        }
                    },
                    err => {
                        reject({
                            code: -1,
                            msg: '查询用户失败。'
                        })
                    }
                )
        })
    },

    // 9. 统计不同性别的用户
    count(user_sex) {
        if (user_sex == '男' || user_sex == '女') {
            let sql = `select count(*) as total from c_user where user_sex='${user_sex}'`
            return new Promise((resolve, reject) => {
                db.query(sql)
                    .then(
                        rows => {
                            resolve({
                                code: 200,
                                msg: '统计数据成功。',
                                result: [...rows]
                            })
                        },
                        err => {
                            reject({
                                code: -1,
                                msg: '统计数据失败。'
                            })
                        }
                    )
            })
        }
        else 
        if(user_sex == '未知') {
            let sql = `select * from c_user`
            return new Promise((resolve, reject) => {
                db.query(sql)
                    .then(
                        rows => {
                            let total = 0;
                            [...rows].forEach(item=>{
                                if(!item.user_sex){
                                    total +=1;
                                }
                            })
                            resolve({
                                code: 200,
                                msg: '统计数据成功。',
                                result:[{total}]
                            })
                        },
                        err => {
                            reject({
                                code: -1,
                                msg: '统计数据失败。'
                            })
                        }
                    )
            })
        }
        else {
            let sql = 'select count(*) as total from c_user';
            return new Promise((resolve, reject) => {
                db.query(sql)
                    .then(
                        rows => {
                            resolve({
                                code: 200,
                                msg: '统计数据成功。',
                                result: [...rows]
                            })
                        },
                        err => {
                            reject({
                                code: -1,
                                msg: '统计数据失败。'
                            })
                        }
                    )
            })
        }
    }
}